<template>
	<view style="width: 749rpx;">
		<view style="display: flex;flex-direction: column;">
			<!-- 轮播图 -->
			<view style="position: relative;z-index: 2;width: 749rpx;">
				<u-swiper radius="0" width="745rpx" height="740rpx" :index="index" :list="goods_detail.tupian_url" :circular="true" :indicator="true"
					imgMode="scaleToFill" interval='3000'></u-swiper>
			</view>
			<!-- <image style="width: 750rpx;height: 750rpx;" :src=goods_detail.url mode=""></image> -->
			<view style="display: flex;color: red;align-items: flex-end;background-color: white;">
				<view style="margin: 30rpx 0 13rpx 30rpx;">
					<text style="margin:0rpx;">￥</text>
					<text style="font-size: 50rpx;margin:0 10rpx 0 0 ;">{{goods_detail.goods_price}}</text>
					<view style="color: black;">
						{{goods_detail.goods_name}}
					</view>

				</view>
			</view>
		</view>
		<view style="display: flex;width: 749rppx;flex-direction: column;padding-bottom: 200rpx;">
			<view
				style="display: flex; margin: 20rpx 0 10rpx 0;padding: 10rpx 0;justify-content: center; background-color: #eee;">
				商品详情
			</view>
			<!-- <image style="width: 500rpx;background-color: aqua;" src="https://img.96weixin.com/ueditor/20250521/1747836335431249.jpg" mode=""></image> -->
			<!-- 代码格式转成富文本格式 -->
			<view class="" style="padding: 20rpx;" v-html="goods_detail.goods_detail">		</view>
		</view>
		<!-- 最下面一行 -->
		<view class="bottom">
			<view style="display:flex;justify-content: space-between;flex-direction: row;width: 100%;">
				<view class="left">
					<navigator class="iconbox" open-type="switchTab" url="/pages/shouye/shouye">
						<image src="../../static/tabbar/chanpin_h.png" mode=""></image>
						<view>商城首页</view>
					</navigator>
					<navigator class="iconbox" open-type="switchTab" url="/pages/gouwuche/gouwuche">
						<image src="../../static/tabbar/gouwuche_active.png" mode=""></image>
						<view>购物车</view>
					</navigator>
				</view>
				<view class="right">
					<view class="pay1" @click="add_gouwuche_popup">
						加入购物车
					</view>
					<view class="pay" @click="pay">
						立即购买
					</view>
				</view>
			</view>
		</view>
		<uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0">
			<view
				style="display: flex;flex-direction: column; background-color: white;width: 100%;height:900rpx;">
				<view style="display: flex;margin: 20rpx 0 0 20rpx;">
					<view style="display: flex;	">
						<image style="width: 220rpx;height: 220rpx;border-radius: 15rpx;"
							:src="goods_detail.tupian_url[0].url" mode=""></image>
					</view>
					<view style="display: flex;flex-direction: column;color: #666666;padding-left: 20rpx;">
						<text style="margin-top: 5rpx;color: #E56844;font-weight: bold;font-size: 35rpx;">￥{{goods_detail.goods_price}}</text>
						<text style="margin-top: 5rpx;">库存：{{yixuan_kucun}}</text>
						<text style="margin-top: 5rpx;">已选择：{{yixuanze}}</text>
					</view>
				</view>
				<view style="width: 100%;height: 2rpx;background-color:#E8E8E8;margin: 20rpx 0;">
				</view>
				<view style="margin-left: 20rpx;">
					选择型号：
				</view>
				<view style="display: flex;flex-wrap: wrap;width: 730rpx; margin:15rpx 0 0 20rpx ;">
					<view v-if="item.kucun!==0" v-for="(item,index) in kucunlist" :key="index" class="spec-item"
						:class="{ selected: selectedIndex === index }" @click="handleSelect(index)">
						{{item.color}}-{{item.size}}
					</view>
				</view>
				<view style="width: 100%;height: 2rpx;background-color:#E8E8E8;margin: 15rpx 0;">
				</view>
				<view style="margin-left: 20rpx;">
					数量
				</view>
				<view style="margin:15rpx 0 0 20rpx ;">
					<uni-number-box :min="1" :max="yixuan_kucun" :value="count" @change="handleChange"></uni-number-box>
				</view>
			</view>
			<view @click="add_gouwuche" style="position: fixed;bottom: 0;font-size: 35rpx; display: flex;height: 100rpx;width: 100%;justify-content: center;align-items: center;background-color: red;color: white;">
				确 认
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				meiyi_name_tel:'',
				jingshouren:'',
				count: 1,
				yixuan_kucun: 0,
				yixuanze: '',
				selectedIndex: -1, // 选中索引
				goods_id: 0, // 商品ID
				goods_canshu: [], // 商品参数
				goods_kucun: [], // 商品库存
				kucunlist: [], // 库存列表
				index: 0,
				goods_detail: {},
			}
		},
		onLoad() {
			let meiyi_name_tel=uni.getStorageSync('meiyi_name_tel')
			this.jingshouren=meiyi_name_tel.name+meiyi_name_tel.mobile
			this.meiyi_name_tel=meiyi_name_tel
			let res = uni.getStorageSync('goods_detail')
			this.goods_detail = res
			this.goods_detail.goods_detail = goods_detail.goods_detail.replace(
			  /<img/g,
			  '<img style="width:100%;height:auto;display:block;"'
			);
			this.goods_id = res._id
			this.suan_kucun_list()
			console.log(this.goods_detail);
		},
		methods: {
			add_gouwuche(){
				const shuju={
					goods_id:this.goods_id,
					count:this.count,
					color:this.yixuanze.split('-')[0],
					size:this.yixuanze.split('-')[1],
					creat_time:Date.now(),
					user_id:this.meiyi_name_tel._id
				}
				uniCloud.callFunction({ 
					name: "fun1",
					data: {
						leixing: 14,
						shuju:shuju
					}
				}).then(res => {
					// 关闭弹窗
					this.$refs.popup.close()
					// 提示添加成功
					uni.showToast({
						title: '添加成功',
						icon: 'success',
						duration: 2000
					})
				})
			},
			handleChange(e) {
				this.count = e
			},
			handleSelect(n) {
				this.count = 1
				this.yixuan_kucun = this.kucunlist[n].kucun
				this.yixuanze= this.kucunlist[n].color + '-' + this.kucunlist[n].size
				this.selectedIndex = this.selectedIndex === n ? -1 : n
			},
			open() {
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
				this.$refs.popup.open()
			},
			add_gouwuche_popup() {
				this.open()
			},
			async suan_kucun_list() {
				await this.get_goods_canshu()
				await this.get_goods_kucun()
				// 将 goods_kucun 转换为 Map 提高查询效率
				const inventoryMap = new Map();
				this.goods_kucun.forEach(item => {
					const key = `${item.color}-${item.size}`; // 唯一标识符
					inventoryMap.set(key, item.kucun);
				});

				// 生成带有更新库存的新数组（保持原数组不变）
				const newKucunlist = await this.kucunlist.map(item => ({
					...item, // 保留原属性
					goods_id: this.goods_id,
					kucun: inventoryMap.get(`${item.color}-${item.size}`) || 0 // 匹配库存，无则默认为0
				}));

				// 使用新数组（根据场景选择是否替换原数组）
				this.kucunlist = newKucunlist;
			},
			// 获取商品参数（返回 Promise 链）
			get_goods_canshu() {
				return uniCloud.callFunction({ // 关键点：返回 Promise
					name: "fun1",
					data: {
						leixing: 8
					}
				}).then(res => {
					this.goods_canshu = res.result.data;
					this.kucunlist = [];
					// 生成库存初始结构
					this.goods_canshu[0].canshu.forEach(item1 => {
						this.goods_canshu[1].canshu.forEach(item2 => {
							this.kucunlist.push({
								color: item1,
								size: item2,
								kucun: 0
							});
						});
					});
				});
			},
			// 获取实际库存（返回 Promise）
			get_goods_kucun() {
				return uniCloud.callFunction({ // 关键点：返回 Promise
					name: "fun1",
					data: {
						leixing: 10,
						tiaojian: {
							goods_id: this.goods_id
						}
					}
				}).then(res => {
					this.goods_kucun = res.result.data;
				});
			},
			pay() {
				uni.navigateTo({
					url: '/pages/confirm/confirm'
				})
			},
		}
	}
</script>

<style lang="scss">
	/* 在App.vue或页面的style中 */
	.rich-text img {
		  width: 749rpx;
		  height: auto;
		}
	

	.container {
		padding: 20rpx;
	}

	/* 规格容器 */
	.specs-box {
		display: flex;
		flex-wrap: wrap;
		width: 730rpx;
		margin: 10rpx;
	}

	/* 单个规格项 */
	.spec-item {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 170rpx;
		height: 60rpx;
		margin: 0 10rpx 15rpx 0;
		border-radius: 5rpx;
		font-size: 24rpx;
		transition: all 0.3s;

		/* 默认未选中样式 */
		background-color: #FFFFFF;
		color: #333333;
		border: 1rpx solid #CCCCCC;
	}

	/* 选中状态样式 */
	.spec-item.selected {
		background-color: #F84E4E !important;
		color: #FFFFFF !important;
		border: 1rpx solid #F84E4E;
	}

	/* 点击态效果 */
	.spec-item:active {
		opacity: 0.8;
	}

	.page {
		background-color: #eee;
	}

	.img {
		max-width: 96%;
		max-height: 100%;
		margin: 0 auto;
	}

	.bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		background: #fff;
		padding: 24rpx 20rpx;
		display: flex;
		border-top: 2rpx solid #ddd;

		.left {
			display: flex;
			width: 75%;
			align-items: center;
			padding: 0 15rpx;
			justify-content: space-around;

			.iconbox {
				font-size: 28rpx;
				position: relative;
				text-align: center;

				image {
					width: 45rpx;
					height: 45rpx;
					margin: 0 auto 4rpx;
				}

				// >view {
				// 	transform: scale(.9);
				// }
			}
		}

		.right {
			display: flex;
			width: 100%;
			font-size: 26rpx;

			>view {
				width: 100%;
				padding: 16rpx 0;
			}

			.pay1 {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 45%;
				font-size: 30rpx;
				color: #fff;
				background: #FF9450;
			}

			.pay {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 45%;
				font-size: 30rpx;
				color: #fff;
				background: #FE2C56;
			}
		}
	}
</style>